import React, { Component } from 'react';
import { Route } from 'react-router-dom'
import { TabBar } from 'antd-mobile';
import './index.scss';
// 子组件
import News from '../News';
import HouseList from '../HouseList';
import Index from '../Index';
import Profile from '../Profile';

const tabItems = [
  {
    title: '首页',
    icon: 'icon-ind',
    path: '/home'
  },
  {
    title: '找房',
    icon: 'icon-findHouse',
    path: '/home/list'
  },
  {
    title: '资讯',
    icon: 'icon-infom',
    path: '/home/news'
  },
  {
    title: '我的',
    icon: 'icon-my',
    path: '/home/profile'
  },
]
/**
 * 点击首页导航菜单，导航到列表页面时，菜单没有高亮
 * 原因：我们实现功能时纸考虑第一次加载和点击导航时的情况
 * 而没有考虑路由切换
 * 解决： 路由切换时，菜单高亮,使用 componentDidUpdate 钩子函数
 */
export default class Home extends Component {
  state = {
    // 默认选中当前路径
    selectedTab: this.props.location.pathname
  };

  componentDidUpdate(preProps) {
    // 菜单高亮
    if (preProps.location.pathname === this.props.location.pathname) return;
    this.setState({
      selectedTab: this.props.location.pathname
    });
  }

  render() {
    return (
      <div className="home">
        {/* 子路由: 最好按顺序排序,首页不能模糊匹配 */}
        <Route exact path={tabItems[0].path} component={Index} />
        <Route path={tabItems[1].path} component={HouseList} />
        <Route path={tabItems[2].path} component={News} />
        <Route path={tabItems[3].path} component={Profile} />
        {/* TabBar */}
        <TabBar
          tintColor="#21b97a"
          barTintColor="white"
          noRenderContent={true}
        >
          {this.renderTabBarItem()}
        </TabBar>
      </div >
    )
  }
  renderTabBarItem() {
    return tabItems.map(item =>
      <TabBar.Item
        icon={<span className={'iconfont ' + item.icon}></span>}
        selectedIcon={<span className={'iconfont ' + item.icon}></span>}
        title={item.title}
        key={item.title}
        selected={this.state.selectedTab === item.path}
        onPress={() => {
          this.setState({
            selectedTab: item.path,
          });
          this.props.history.push(item.path);
        }}
      ></TabBar.Item>
    )
  }
}
